package com.sjft.cloud.commons.core.encrypt;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import com.sjft.cloud.commons.core.func.Fn;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class AESEncryptHandler extends BaseTypeHandler {

    public static String key = "AD42F697B035CKU9";

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, AESEncoder.encrypt4Aes((String) parameter, key));
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String columnValue = rs.getString(columnName);
        String value = AESDecoder.decrypt4Aes2Str(columnValue, key);
        return Fn.isNotEmpty(value) ? value : columnValue;
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String columnValue = rs.getString(columnIndex);
        String value = AESDecoder.decrypt4Aes2Str(columnValue, key);
        return Fn.isNotEmpty(value) ? value : columnValue;
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        String columnValue = cs.getString(columnIndex);
        return AESDecoder.decrypt4Aes2Str(columnValue, key);
    }

    public static void main(String [] args){
       String name1 = AESDecoder.decrypt4Aes2Str("5KrQY2mzMer32IOwddkkDQ==", key);
       String value1 = AESDecoder.decrypt4Aes2Str("IbgboXFvhlOjNoyuYA+xq4ob24q/dVLo0Pujz2+9CfA=", key);
           }
}
